package com.world.rickcloudendpoint.queue;

import java.util.Arrays;

/**
 * @description: 环形队列：方式1
 * @author: jlsong
 * @date: 2022/05/30 09:01:26
 * @version: 1.0
 */
public class CircularList<T> {
    // 数组容量
    private int capacity;
    // 读位置
    public int readPos = -1;
    // 写位置
    public int writePos = -1;
    // 数据容器
    private T[] items;

    public CircularList(int capacity) {
        this.capacity = capacity;
        items = (T[]) new Object[capacity];
    }

    // 向队列放入元素
    public void enqueue(T item) {
        incrementWritePos();
        items[writePos] = item;
    }

    // 从队列中读取元素
    public T dequeue() {
        incrementReadPos();
        T item = items[readPos];
        items[readPos] = null;

        // Rest the reading and writing positions if the circle is empty
        if (readPos == writePos) {
            readPos = -1;
            writePos = -1;
        }
        return item;
    }

    // 增加写位置
    public void incrementWritePos() {
        writePos++;

        // Write-position reached the bottom of the array
        if (writePos == capacity) {
            writePos = 0;
            if (readPos == -1) {
                readPos = 0;
            }
            return;
        }

        if (writePos == readPos) {
            incrementReadPos();
        }
    }

    // 增加读位置
    public void incrementReadPos() {
        readPos++;

        // Read-position reached the bottom of the array
        if (readPos == capacity) {
            readPos = 0;
        }
    }

    public String toString() {
        return Arrays.toString(items);
    }
}
